package com.back.service.impl;

import com.back.dto.CompanyDTO;
import com.back.entity.Company;
import com.back.entity.CompanyRecruiter;
import com.back.mapper.CompanyMapper;
import com.back.mapper.CompanyRecruiterMapper;
import com.back.service.ICompanyService;
import com.back.vo.CompanyVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  企业服务实现类
 * </p>
 *
 * @author liyang
 * @since 2025-04-26
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {

    @Autowired
    private CompanyRecruiterMapper companyRecruiterMapper;

    @Override
    public IPage<CompanyVO> getCompanyList(Page<Company> page, String industry, String status, String keyword) {
        // 构建查询条件
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        
        // 行业筛选
        if (StringUtils.isNotBlank(industry)) {
            queryWrapper.eq(Company::getIndustry, industry);
        }
        
        // 状态筛选
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(Company::getVerificationStatus, status);
        }
        
        // 关键词搜索 - 公司名称
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(Company::getName, keyword);
        }
        
        // 只查询未删除的
        queryWrapper.eq(Company::getDeleted, false);
        
        // 排序
        queryWrapper.orderByDesc(Company::getCreateTime);
        
        // 执行分页查询
        Page<Company> companyPage = page(page, queryWrapper);
        
        // 转换为VO
        Page<CompanyVO> resultPage = new Page<>();
        BeanUtils.copyProperties(companyPage, resultPage, "records");
        
        // 转换记录
        List<CompanyVO> companyVOList = companyPage.getRecords().stream().map(company -> {
            CompanyVO companyVO = new CompanyVO();
            BeanUtils.copyProperties(company, companyVO);
            return companyVO;
        }).collect(Collectors.toList());
        
        resultPage.setRecords(companyVOList);
        
        return resultPage;
    }

    @Override
    public CompanyVO getCompanyDetail(Long id) {
        // 查询公司
        Company company = getById(id);
        if (company == null || company.getDeleted()) {
            return null;
        }
        
        // 转换为VO
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(company, companyVO);
        
        return companyVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CompanyVO createCompany(CompanyDTO companyDTO, Long userId) {
        // 创建公司实体
        Company company = new Company();
        BeanUtils.copyProperties(companyDTO, company);
        
        // 设置其他属性
        company.setUserId(userId);
        company.setVerificationStatus("pending"); // 默认待审核
        long currentTime = System.currentTimeMillis();
        company.setCreateTime(currentTime);
        company.setUpdateTime(currentTime);
        company.setDeleted(false);
        
        // 保存到数据库
        save(company);
        
        // 创建企业管理员关联
        CompanyRecruiter recruiter = new CompanyRecruiter();
        recruiter.setUserId(userId);
        recruiter.setCompanyId(company.getId());
        recruiter.setIsAdmin(true);
        recruiter.setCreateTime(currentTime);
        recruiter.setUpdateTime(currentTime);
        recruiter.setDeleted(false);
        companyRecruiterMapper.insert(recruiter);
        
        // 转换为VO返回
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(company, companyVO);
        
        return companyVO;
    }

    @Override
    public CompanyVO updateCompany(Long id, CompanyDTO companyDTO) {
        // 查询公司
        Company company = getById(id);
        if (company == null || company.getDeleted()) {
            return null;
        }
        
        // 更新属性
        BeanUtils.copyProperties(companyDTO, company);
        company.setUpdateTime(System.currentTimeMillis());
        
        // 保存到数据库
        updateById(company);
        
        // 转换为VO返回
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(company, companyVO);
        
        return companyVO;
    }

    @Override
    public boolean deleteCompany(Long id) {
        // 查询公司
        Company company = getById(id);
        if (company == null || company.getDeleted()) {
            return false;
        }
        
        // 逻辑删除
        company.setDeleted(true);
        company.setUpdateTime(System.currentTimeMillis());
        
        return updateById(company);
    }

    @Override
    public String uploadLogo(Long id, String logoUrl) {
        // 查询公司
        Company company = getById(id);
        if (company == null || company.getDeleted()) {
            return null;
        }
        
        // 更新logo
        company.setLogo(logoUrl);
        company.setUpdateTime(System.currentTimeMillis());
        updateById(company);
        
        return logoUrl;
    }

    @Override
    public String uploadBusinessLicense(Long id, String licenseUrl) {
        // 查询公司
        Company company = getById(id);
        if (company == null || company.getDeleted()) {
            return null;
        }
        
        // 更新营业执照
        company.setBusinessLicense(licenseUrl);
        company.setUpdateTime(System.currentTimeMillis());
        updateById(company);
        
        return licenseUrl;
    }

    @Override
    public boolean checkCompanyPermission(Long companyId, Long userId) {
        // 首先检查该公司是否存在
        Company company = getById(companyId);
        if (company == null || company.getDeleted()) {
            return false;
        }
        
        // 检查是否是企业创建者
        if (company.getUserId().equals(userId)) {
            return true;
        }
        
        // 检查是否是企业管理员
        LambdaQueryWrapper<CompanyRecruiter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyRecruiter::getCompanyId, companyId)
                    .eq(CompanyRecruiter::getUserId, userId)
                    .eq(CompanyRecruiter::getIsAdmin, true)
                    .eq(CompanyRecruiter::getDeleted, false);
        
        return companyRecruiterMapper.selectCount(queryWrapper) > 0;
    }
}
